package com.study.boot;

import com.study.handler.UserServerHandler;
import com.study.model.RpcRequest;
import com.study.serializer.JSONSerializer;
import com.study.serializer.RpcDecoder;
import com.study.service.UserServiceImpl;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ServerBootstrap implements InitializingBean, ApplicationContextAware {

    @Autowired
    private UserServiceImpl userServiceImpl;

    private ApplicationContext applicationContext;

    //hostName:ip地址  port:端口号
    public void startServer() throws InterruptedException {
        new Thread(()->{
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast(new StringEncoder());
                                pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                                pipeline.addLast(new UserServerHandler(applicationContext));

                            }
                        });
                ChannelFuture cf =serverBootstrap.bind("127.0.0.1", 8990).sync();
            }catch (InterruptedException e) {
                e.printStackTrace();
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }).start();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        startServer();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
